<template>
  <div class="addArticle_box">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="17" :xl="17">
        <div class="write_abstract box-card">
          <h4 class="text-color">标题</h4>
          <el-input
            v-model="write.titleValue"
            placeholder="请输入文章标题"
            maxlength="50"
            show-word-limit
            size="large"
            clearable
          />
          <p class="text-color">标示文章、作品内容的简明语句，填写醒目的</p>
        </div>
        <div class="write_abstract box-card">
          <!-- 富文本编辑器 -->
          <WangEditor v-model:value="valueHtml" height="400px" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="24" :lg="7" :xl="7">
        <div class="write_abstract box-card">
          <h4 class="text-color">摘要</h4>
          <el-input
            v-model="write.abstractValue"
            :autosize="{ minRows: 3, maxRows: 5 }"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请简单概述文章内容"
            clearable
          />
        </div>
        <div class="write_abstract box-card">
          <h4 class="text-color">缩略图(不上传则随机一张)</h4>
          <el-input size="large" v-model="write.thumbnailValue" placeholder="请点击上传图片或手动输入图片地址">
            <template #append>
              <el-upload
                ref="uploadEle"
                class="upload-demo"
                :action="uploadURL"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeUploadFunction"
                :show-file-list="false"
              >
                <template #trigger>
                  <el-button>上传图片</el-button>
                </template>
              </el-upload>
            </template>
          </el-input>
          <p class="text-color">注：点击上传的图片地址由系统生成，修改会导致图片失效</p>
        </div>
        <div class="write_abstract box-card">
          <h4 class="text-color">分类</h4>
          <el-select v-model="write.classifyValue" placeholder="请选择文章分类" size="large">
            <el-option v-for="(item, index) in classifyInfo" :label="item.classifyName" :key="index" :value="item.classifyId" />
          </el-select>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="write_abstract box-card">
              <h4 class="text-color">状态</h4>
              <el-select v-model="write.stateValue" placeholder="文章状态" size="large">
                <el-option label="公开" value="1" />
                <el-option label="私密" value="2" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="write_abstract box-card">
              <h4 class="text-color">评论</h4>
              <el-select v-model="write.commentValue" placeholder="评论是否开启" size="large">
                <el-option label="开启" value="1" />
                <el-option label="关闭" value="2" />
              </el-select>
            </div>
          </el-col>
        </el-row>
        <div class="write_abstract" style="text-align: center; background: none">
          <el-button text @click="previewArticleDialogFormVisible = true">预览</el-button>
          <el-button style="width: 50%" plain color="#2fa7b9" @click="submitAdd">提交</el-button>
          <p class="text-color">注：普通用户提交文章需要等待管理员审核</p>
        </div>
      </el-col>
    </el-row>
    <el-dialog v-model="previewArticleDialogFormVisible" title="富文本内容预览" width="1300px" top="50px">
      <div v-highlight class="view" v-html="valueHtml"></div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="addArticle">
import { ref, toRefs, onMounted, reactive, shallowRef, onBeforeUnmount, watch } from "vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { ElMessage, ElNotification } from "element-plus";
import { getClassifyInfo, addArticle, addArticleNum } from "@/api/modules/allApi";
import { useUserStore } from "@/stores/modules/user";
const userStore = useUserStore();
const valueHtml = ref("");
const state = reactive<any>({
  // 当前登录的用户信息
  userInfo: {
    userEmail: "",
    userIcon: "",
    userPass: "",
    userRegdate: "",
    userSignature: "",
    userId: -1,
    userType: -1,
    userName: ""
  },
  // 编写信息
  write: {
    titleValue: "",
    abstractValue: "",
    thumbnailValue: "",
    classifyValue: "",
    stateValue: "1",
    commentValue: "1"
  },
  // 分类信息
  classifyInfo: [],
  // 缩略图上传到服务器的路径
  uploadURL: import.meta.env.VITE_API_URL + "upload/thumbnailUpload",
  // 预览对话框状态
  previewArticleDialogFormVisible: false,
  randImg: ""
});
const loadData = (state: any) => {
  // 查询文章分类
  getClassifyInfo().then(res => {
    state.classifyInfo = res.data;
  });
};
const getRandImg = () => {
  fetch("https://api.vvhan.com/api/bing?type=json&rand=sj")
    .then(response => response.json())
    .then(data => (state.randImg = data.data.url));
};

// 图片上传格式、大小要求
const beforeUploadFunction = (rawFile: any) => {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/jpg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/gif"
  ) {
    ElMessage.error("仅支持图片格式.png | .jpg | .jpeg | .gif ");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("仅支持大小不超过5MB的图片!");
    return false;
  }
  return true;
};

// 图片上传成功后执行的函数
const handleAvatarSuccess = (response: any) => {
  state.write.thumbnailValue = response.data;
};

// 提交
const submitAdd = () => {
  // 获取当前下拉框选中的value 对于的label值
  let obj = {};
  obj = state.classifyInfo.find(item => {
    return item.classifyId === Number(state.write.classifyValue);
  });

  // 判断内容是否填写完整
  if (
    state.write.titleValue != "" &&
    state.write.abstractValue != "" &&
    state.write.classifyValue != "" &&
    state.write.stateValue != "" &&
    state.write.commentValue != ""
  ) {
    // 添加文章
    const params = {
      userId: state.userInfo.userId, // 编写用户编号
      userName: state.userInfo.userName, // 编写用户名称
      articleTitle: state.write.titleValue, // 文章标题
      articleClassifyId: state.write.classifyValue, // 分类编号
      articleClassifyName: obj.classifyName, // 分类名称
      articleDase: state.write.abstractValue, // 文章描述
      articleImgLitimg: state.write.thumbnailValue || state.randImg, // 文章缩略图
      articleContent: valueHtml.value, // 文章内容
      articleState: parseInt(state.write.stateValue), // 文章状态
      articlePass: state.userInfo.userType == 0 ? 2 : 1, // 审核(1待审核，2审核通过，3审核失败) 判断当前用户时普通用户(1)还是管理员(1)
      commentState: parseInt(state.write.commentValue) // 文章评论状态
    };

    addArticle(params).then(res => {
      if (res.code == 0) {
        // 增加分类对应的文章数量  +1
        const params = {
          classifyId: state.write.classifyValue
        };
        addArticleNum(params).then(res => {
          // 清空编写的文章内容
          valueHtml.value = "<p></p>";
          state.write = {
            titleValue: "",
            abstractValue: "",
            thumbnailValue: "",
            classifyValue: "",
            stateValue: "1",
            commentValue: "1"
          };
          ElNotification({
            title: "提示",
            message: state.userInfo.userType == 0 ? "文章发布成功！" : "文章提交成功，等待管理员审核",
            type: "success"
          });
        });
      }
    });
  } else {
    ElMessage.error("除缩略图之外的内容都是必填项哦~");
  }
};
onMounted(() => {
  state.userInfo = userStore.userData.data[0];
  loadData(state);
  getRandImg();
});
const { userInfo, write, classifyInfo, uploadURL, previewArticleDialogFormVisible } = toRefs(state);
</script>

<style scoped lang="scss">
.addArticle_box {
  width: 100%;
  height: auto;
}
.addArticle_box > h3 {
  padding: 20px;
  margin-bottom: 10px;
  color: #2fa7b9;
  background-color: white;
}
.write_abstract {
  padding: 10px 20px;
  margin-bottom: 10px;
  text-align: left;
  background: white;
}
.write_abstract h4 {
  color: #8f8f8f;
}
.write_abstract p {
  font-size: 12px;
  color: #8f8f8f;
}
.el-select {
  width: 100%;
}
:deep(.el-input-group__append) {
  width: 70px;
}

/* 富文本编辑器样式 */
:deep(.w-e-bar) {
  padding: 15px 5px;
  font-size: 15px;
  color: #8b8b8b;
  background-color: #ffffff;
  border-bottom: 1px solid #ececec;
}
:deep(.w-e-bar-divider) {
  background-color: white;
}
:deep(.w-e-bar svg) {
  fill: #8b8b8b;
}
:deep(.w-e-bar-item button) {
  color: #8b8b8b;
}
:global(.w-e-full-screen-container) {
  z-index: 999 !important;
}
:deep(.w-e-bar-item .active) {
  background-color: #e8e8e8;
}
</style>
